package server_commands;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Vector;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

public class CONT_LISTCommand extends Command {

	
	public CONT_LISTCommand(String parameter) {
		setCode(CONT_LIST_CMD);
		setParameter(parameter);
	}
	
	
	@SuppressWarnings("unchecked")
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {

		String username = getParameter();
		
		String contactListQuery = "SELECT tblUsers.username, tblUsers.nickname, tblUsers.email, tblUsers.ip_address, tblUsers.local_address, tblUsers.port, tblUsers.status, tblUsers.reg_date, tblUsers.avatar " +
								  "FROM tblUsers, tblContacts " +
								  "WHERE tblContacts.user_source='" + username +"' AND tblUsers.username=tblContacts.user_dest";
		
		try {
			dbConnection.doStatement(contactListQuery);
		
			ArrayList<Vector> contactList = new ArrayList<Vector>(dbConnection.data);
		
			dbConnection.clearDataStore();
		
			String blockListQuery = "SELECT tblBlocks.user_source FROM tblBlocks " +
				"WHERE tblBlocks.user_dest = '" + username + "'";
		
			dbConnection.doStatement(blockListQuery);

			ArrayList<Vector> blockList = new ArrayList<Vector>(dbConnection.data);
			
			connection.setMessage( "120 Contacts " + contactList.size() );
			
			ListIterator iterator = blockList.listIterator();
			
			Vector<String> blockedNames = new Vector<String>();
			while ( iterator.hasNext() ) {
				blockedNames.add( ((Vector<String>)iterator.next()).get(0) ); 
			}
			
			
			// Svi korisnici koji su blokirali ovog korisnika prikazuju se u
			// njegovoj kontakt listi kao Offline.
			for (int i = 0; i < contactList.size(); i++) {
				StringBuffer entry = new StringBuffer();
				
				for (int j = 0; j < contactList.get(i).size(); j++) {
					
					if (j == 6) {
						if ( blockedNames.contains(contactList.get(i).get(0)) ) {
							contactList.get(i).set(j, "Offline");
						}
					}
					
					entry.append(contactList.get(i).get(j));
					if (j < contactList.get(i).size() - 1) {
						entry.append(" ");
					}
				}			
	
				connection.setMessage(entry.toString());
			}
			
			
			dbConnection.clearDataStore();
		
		} catch (SQLException e) {			
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}
	
}
